﻿using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestPetaPoco.Models;

namespace TestPetaPoco.Common
{
    public class BaseController<TService> : Controller
    {
        /// <summary>
        /// Auto Try Action To Response Result
        /// </summary>
        /// <param name="action">funAction</param>
        /// <returns>
        /// Response Result
        /// </returns>
        ///   public UserEws Member = null;

        public BaseController()
        {
          //  Service = EngineContext.Current.Resolve<TService>();
            if (Member == null)
            {
                Member = MemberContext2.Member;
            }
        }

        public TService Service
        {
            get;
            private set;
        }
        public ResponseModel ActionResponse(Func<ResponseModel> action)
        {
            ResponseModel result = new ResponseModel();
            const string LOG_FORMAT = "message:{0} [END] url:{1} [END] args:{2}";
            string message = "执行成功";
            string url = this.Request.Url.AbsoluteUri;
            if (this.Request.Url.AbsoluteUri.IndexOf('?') > 0)
            {
                url = this.Request.Url.AbsoluteUri.Substring(0, this.Request.Url.AbsoluteUri.IndexOf('?'));
            }
            List<string> args = new List<string>();
            string[] excludes = { "key", "password", ".ASPXAUTH", "ASP.NET_SessionId", MemberContext2.COOKIE_EMAIL_KEY };
            foreach (var key in this.Request.Params.AllKeys)
            {
                if (key.Equals("ALL_HTTP")) break;
                if (excludes.Contains(key)) continue;
                args.Add(string.Format("{0}={1}", key, this.Request.Params[key]));
            }
            string argsString = string.Join("&", args);

            result = action.Invoke();
            if (!result.IsSuccess)
            {
                message = result.ResponseError.Message;
               // LogHelper.WarnFormat(LOG_FORMAT, message, url, argsString);
            }
            else
            {
               // LogHelper.InfoFormat(LOG_FORMAT, message, url, argsString);
            }
            return result;
        }

        /// <summary>
        /// Auto Try Action To Response String
        /// </summary>
        /// <param name="action">funAction</param>
        /// <returns>Response String</returns>
        public string ActionResponseGetString(Func<ResponseModel> action, object checkedKeys = null, bool isValid = true)
        {
            ResponseModel result;
            if (!isValid)
            {
                result = new ResponseModel
                {
                    IsSuccess = false,
                    ResponseError = new ResponseError(ResponseErrorCode.DataConstraint, "数据验证失败")
                };
            }
            else
            {
                result = ActionResponse(action);
                if (checkedKeys != null)
                {
                    result.CheckedKey = checkedKeys;
                }
            }
            if ((string.Compare(Request.Path, "/api/ProductRackStock/GetProductWithStock", true)) == 0)
            {
               // LogHelper.Warn(string.Format("调用/api/ProductRackStock/GetProductWithStock接口在序列化返回数据前打印\n"));
            }
            return JsonHelper.SerializeObject(result);

        }

        /// <summary>
        /// Get ResponseModel By ResultSet
        /// </summary>
        /// <param name="rs">ResultSet</param>
        /// <returns>Model</returns>
        public ResponseModel GetResponseByResultSet(ResultSet rs)
        {
            var responseModel = new ResponseModel();
            if (!rs.IsSuccess)
            {
                responseModel.Data = rs.Data;
                responseModel.IsSuccess = rs.IsSuccess;
                responseModel.ResponseError = new ResponseError(ResponseErrorCode.DataConstraint, rs.Message);
                responseModel.Message = responseModel.ResponseError.Message;
                responseModel.ResponseError.Code2 = rs.Code;
            }
            else
            {
                responseModel.Data = rs.Data;
                responseModel.CheckedKey = rs.CheckedKey;
                if (!string.IsNullOrEmpty(rs.Message))
                {
                    responseModel.Message = rs.Message;
                }
            }
            return responseModel;
        }

        /// <summary>
        /// 获取当前语言集合
        /// </summary>
        /// <summary>
        /// Gets the script search.
        /// </summary>
        /// <param name="search">The search.</param>
        /// <returns></returns>
        public List<ScriptSearch> GetScriptSearch(string search)
        {
            List<ScriptSearch> result = new List<ScriptSearch>();
            string[] bases = search.Split('|');
            string[] tables = bases[0].Split('`');
            string[] columns = bases[1].Split('`');
            string[] values = bases[2].Split('`');
            string[] operates = bases[3].Split('`');

            if (tables.Length < 1 || columns.Length < 1 || values.Length < 1 || operates.Length < 1)
                return result;

            if (values.Length == 1 && values[0].Length < 1)
                return result;

            for (int i = 0; i < tables.Length; i++)
            {
                if (values[i].Length < 1 || columns[i].Length < 1)
                {
                    continue;
                }
                ScriptSearch scriptSearch = new ScriptSearch
                {
                    Column = columns[i],
                    TableName = tables[i],
                    Value = values[i]

                };

                if (string.IsNullOrEmpty(operates[i]))
                {
                    scriptSearch.Operate = OperateType.Like;
                }
                else
                {
                    scriptSearch.Operate = EnumParse<OperateType>(operates[i]);
                }
                result.Add(scriptSearch);
            }
            return result;
        }
        public static T EnumParse<T>(string value)
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }

        public UserInfo Member = null;

        public static class JsonHelper
        {
            /// <summary>
            /// 序列化
            /// </summary>
            /// <param name="value"></param>
            /// <returns></returns>
            public static string SerializeObject(object value)
            {
                Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                timeConverter.DateTimeFormat = "yyyy'/'MM'/'dd' 'HH':'mm':'ss";

                return Newtonsoft.Json.JsonConvert.SerializeObject(value, timeConverter);
            }

            /// <summary>
            /// 反序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="value"></param>
            /// <returns></returns>
            public static T DeserializeObject<T>(string value)
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
            }

            public static string SerializeObjectToJson<T>(T List)
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(List);
            }

            public static T DeserializeObjectToList<T>(string List)
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(List);
            }
        }
        
    }
    public static class PagingExt
    {
        public static object JsonPage(this PageTable page)
        {
            return new
            {
                iTotalRecords = page.TotalItems,
                iTotalDisplayRecords = page.TotalItems,
                aaData = page.Table
            };
        }

        public static object JsonPage(this PageTable page, object assistantData)
        {
            return new
            {
                iTotalRecords = page.TotalItems,
                iTotalDisplayRecords = page.TotalItems,
                aaData = page.Table,
                AssistantData = assistantData
            };
        }
    }
}